/**
 * @param {number[][]} heights
 * @return {number[][]}
 */
var pacificAtlantic = function(heights) {

  let pacific = false, atlantic = false, result = [], visited = new Array(heights.length), indexI, indexJ;
  for(let i = 0; i < heights.length; i++) {
    visited[i] = new Array(heights[0].length).fill(false);
  }
  // 判断是否为太平洋的边上，即：上边界与左边界
  function isPacificOceanBorder(i, j) {
    return i == 0 || j == 0;
  }
  // 判断是否为大西洋的边上，即：下边界与右边界
  function isAtlanticOceanBorder(i, j) {
    return i == heights.length - 1 || j == heights[0].length - 1;
  }
  // 判断位置是否有效
  function isValidPosition(i, j) {
    return (i < heights.length && i >= 0) && (j < heights[0].length && j >= 0);
  }


  function dfs(i, j) {
    if(pacific && atlantic) {
      return;
    }
    if(isPacificOceanBorder(i, j)) {
      pacific = true;
    }
    if(isAtlanticOceanBorder(i, j)) {
      atlantic = true;
    }
    // 上
    if(isValidPosition(i - 1, j) && !visited[i - 1][j] && heights[i - 1][j] <= heights[i][j]) {
      visited[i - 1][j] = true;
      dfs(i - 1, j);
      visited[i - 1][j] = false;
    }
    // 下
    if(isValidPosition(i + 1, j) && !visited[i + 1][j] && heights[i + 1][j] <= heights[i][j]) {
      visited[i + 1][j] = true;
      dfs(i + 1, j);
      visited[i + 1][j] = false;
    }
    // 左
    if(isValidPosition(i, j - 1) && !visited[i][j - 1] && heights[i][j - 1] <= heights[i][j]) {
      visited[i][j - 1] = true;
      dfs(i, j - 1);
      visited[i][j - 1] = false;
    }
    // 右
    if(isValidPosition(i, j + 1) && !visited[i][j + 1] && heights[i][j + 1] <= heights[i][j]) {
      visited[i][j + 1] = true;
      dfs(i, j + 1);
      visited[i][j + 1] = false;
    }
  }

  function resetVisited() {
    for(let i = 0; i < heights.length; i++) {
      for(let j = 0; j < heights[0].length; j++) {
        heights[i][j] = false;
      }
    }
  }

  for(let i = 0; i < heights.length; i++) {
    for(let j = 0; j < heights[0].length; j++) {
      dfs(i, j);
      if(pacific && atlantic) {
        result.push([i, j]);
      }
      if(pacific) {
        pacific = false;
      }
      if(atlantic) {
        atlantic = false;
      }
    }
  }
  return result;
};
let heights = [[1,2,2,3,5],[3,2,3,4,4],[2,4,5,3,1],[6,7,1,4,5],[5,1,1,2,4]];
console.log(pacificAtlantic(heights));
heights = [[2,1],[1,2]];
console.log(pacificAtlantic(heights));
